package com.ifacebox.web.admin.master.dao;

import com.ifacebox.web.admin.master.model.MasterNotice;
import com.ifacebox.web.admin.master.model.MasterNoticeQuery;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author znn
 */
@Mapper
@Component
public interface MasterNoticeDao {

    @Select({"<script>"
            , "SELECT * FROM"
            , "( SELECT *,id IN ( SELECT notice_id FROM master_user_notice WHERE user_id = #{userId} ) AS status_id FROM master_notice ) AS t"
            , "<where>"
            , "<if test='createUser != null and !createUser.isEmpty()'>( t.receive_user IN ( '', #{createUser} ) OR t.create_user = #{createUser} )</if>"
            , "<if test='statusId != null'>AND t.status_id = #{statusId}</if>"
            , "</where>"
            , "ORDER BY t.create_time DESC LIMIT #{offset}, #{limit}"
            , "</script>"})
    List<MasterNotice> query(MasterNoticeQuery masterNoticeQuery);

    @Select({"<script>"
            , "SELECT COUNT(*) FROM"
            , "( SELECT *,id IN ( SELECT notice_id FROM master_user_notice WHERE user_id = #{userId} ) AS status_id FROM master_notice ) AS t"
            , "<where>"
            , "<if test='createUser != null and !createUser.isEmpty()'>( t.receive_user IN ( '', #{createUser} ) OR t.create_user = #{createUser} )</if>"
            , "<if test='statusId != null'>AND t.status_id = #{statusId}</if>"
            , "</where>"
            , "</script>"})
    Long total(MasterNoticeQuery masterNoticeQuery);

    @Select({"<script>"
            , "SELECT * FROM master_notice WHERE id= #{id}"
            , "</script>"})
    MasterNotice queryById(Integer id);

    @Insert({"<script>"
            , "INSERT INTO master_notice"
            , "( title, content, receive_user, create_user ) VALUES ( #{title}, #{content}, #{receiveUser}, #{createUser} )"
            , "</script>"})
    @Options(useGeneratedKeys = true, keyProperty = "id")
    Integer save(MasterNotice masterNotice);

    @Update({"<script>"
            , "UPDATE master_notice SET"
            , "title = #{title}, content = #{content}, receive_user = #{receiveUser}, update_user = #{updateUser}, update_time = now()"
            , " WHERE id = #{id}"
            , "</script>"})
    Integer edit(MasterNotice masterNotice);

    @Delete({"<script>"
            , "DELETE FROM master_notice WHERE id = #{id}"
            , "</script>"})
    Integer delete(Integer id);
}
